package com.geekchique.runningbuddy.view;

import com.geekchique.runningbuddy.R;
import android.content.Context;
import android.text.Layout.Alignment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.geekchique.runningbuddy.controller.IStopClockController;
import com.geekchique.runningbuddy.provider.ActivityID;

public class StopwatchView  implements ViewFactory {

	private Context context;
	private TextSwitcher stopClock;
	private Button startStopButton;
	private IStopClockController stopwatchController;

	public StopwatchView(Context context, IStopClockController controller,TextSwitcher stopClock, Button startStopButton) {
		this.context = context;
		this.stopClock = stopClock;
		this.startStopButton = startStopButton;
		this.stopwatchController = controller;

	    stopClock.setFactory(this);

	    Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
	    Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
	    stopClock.setInAnimation(in);
	    stopClock.setOutAnimation(out);

		this.startStopButton.setOnClickListener(executeAStart);

	}

	public TextSwitcher getStopWatch(){
		return this.stopClock;
	}

	public void resetStopClock() {
		this.stopClock.setText( ActivityID.START_TIME );
	}

	public View makeView() {
	    TextView textView = new TextView(context);
	    textView.setAlignment(Alignment.ALIGN_CENTER);
	    textView.setTextSize(50);
	    return textView;
	}

	public void setStopClock(String text){
		this.stopClock.setText(text);
	}

	public void switchStopwatchButton(int stopClockState){

		if(stopClockState == ActivityID.STOPWATCH_RUNNING){
			startStopButton.setText(R.string.button_stop);;
		}else{
			startStopButton.setText(R.string.button_start);;
		}
	}

	private OnClickListener executeAStart = new OnClickListener() {
		public void onClick(View v) {
			stopwatchController.start();
			setStartStopButtonClickListener(executeAStop);
		}
	};

	private OnClickListener executeAStop = new OnClickListener() {

		public void onClick(View v) {
			stopwatchController.stop();
			setStartStopButtonClickListener(executeAStart);
		}
	};


	public void setStartStopButtonClickListener(OnClickListener onClickListener){
		this.startStopButton.setOnClickListener(onClickListener);
	}

}
